import sqlite3
from flask import render_template, request, redirect, url_for, flash, session
from . import web_bp
from models import get_all_users, get_user_by_id, get_user_roles, create_operation_log, get_db_connection

# 用户管理
@web_bp.route('/users')
def users():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    users = get_all_users()
    return render_template('users.html', users=users)

# 添加用户
@web_bp.route('/users/add', methods=['GET', 'POST'])
def add_user():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
        nickname = request.form['nickname']
        
        conn = get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute('INSERT INTO users (username, password, email, nickname) VALUES (?, ?, ?, ?)',
                          (username, password, email, nickname))
            conn.commit()
            flash('用户添加成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加用户', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'username: {username}', '成功', 0)
        except sqlite3.IntegrityError:
            flash('用户名或邮箱已存在')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加用户', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'username: {username}', '用户名或邮箱已存在', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.users'))
    
    return render_template('add_user.html')

# 编辑用户
@web_bp.route('/users/edit/<int:user_id>', methods=['GET', 'POST'])
def edit_user(user_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        nickname = request.form['nickname']
        
        try:
            cursor.execute('UPDATE users SET username=?, email=?, nickname=? WHERE id=?',
                          (username, email, nickname, user_id))
            conn.commit()
            flash('用户信息更新成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '更新用户', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'user_id: {user_id}, username: {username}', '成功', 0)
        except sqlite3.IntegrityError:
            flash('用户名或邮箱已存在')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '更新用户', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'user_id: {user_id}, username: {username}', '用户名或邮箱已存在', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.users'))
    
    # GET请求，显示编辑表单
    cursor.execute('SELECT * FROM users WHERE id=?', (user_id,))
    user = cursor.fetchone()
    conn.close()
    
    if not user:
        flash('用户不存在')
        return redirect(url_for('web.users'))
    
    return render_template('edit_user.html', user=user)

# 删除用户
@web_bp.route('/users/delete/<int:user_id>', methods=['POST'])
def delete_user(user_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    # 先获取用户信息用于日志记录
    user = cursor.execute('SELECT username FROM users WHERE id=?', (user_id,)).fetchone()
    cursor.execute('DELETE FROM users WHERE id=?', (user_id,))
    conn.commit()
    conn.close()
    
    if user:
        flash('用户删除成功')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '删除用户', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'user_id: {user_id}, username: {user[0]}', '成功', 0)
    else:
        flash('用户不存在')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '删除用户', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'user_id: {user_id}', '用户不存在', 0)
    
    return redirect(url_for('web.users'))

# 用户角色分配
@web_bp.route('/users/roles/<int:user_id>', methods=['GET', 'POST'])
def user_roles(user_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    user = get_user_by_id(user_id)
    if not user:
        flash('用户不存在')
        return redirect(url_for('web.users'))
    
    if request.method == 'POST':
        # 获取表单提交的角色ID列表
        selected_role_ids = request.form.getlist('roles')
        
        # 获取用户当前的角色
        current_roles = get_user_roles(user_id)
        current_role_ids = [str(role[0]) for role in current_roles]
        
        # 计算需要添加和删除的角色
        roles_to_add = set(selected_role_ids) - set(current_role_ids)
        roles_to_remove = set(current_role_ids) - set(selected_role_ids)
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        try:
            # 添加新角色
            for role_id in roles_to_add:
                cursor.execute('INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)', (user_id, role_id))
            
            # 删除取消的角色
            if roles_to_remove:
                placeholders = ','.join('?' * len(roles_to_remove))
                cursor.execute(f'DELETE FROM user_roles WHERE user_id = ? AND role_id IN ({placeholders})', 
                              [user_id] + list(roles_to_remove))
            
            conn.commit()
            flash('用户角色分配成功')
            
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '分配用户角色', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'user_id: {user_id}', '成功', 0)
        except Exception as e:
            conn.rollback()
            flash(f'用户角色分配失败: {str(e)}')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '分配用户角色', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'user_id: {user_id}', f'失败: {str(e)}', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.user_roles', user_id=user_id))
    
    # GET请求 - 显示用户角色分配页面
    from models import get_all_roles
    all_roles = get_all_roles()
    user_roles = get_user_roles(user_id)
    user_role_ids = [role[0] for role in user_roles]
    
    return render_template('user_roles.html', user=user, all_roles=all_roles, user_role_ids=user_role_ids)